package com.knife.easyexcel.read.validator.impl;

import com.knife.easyexcel.read.data.ImportDataWarp;
import com.knife.easyexcel.read.data.ImportValidatorContext;
import com.knife.easyexcel.read.validator.ImportValidator;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.logging.log4j.util.Strings;

import java.util.List;
import java.util.Objects;

/**
 * 重复行的校验，主要是用于导入的excel中，判断excel行里面又重复的数据行
 *
 * @author lth
 * @created 2025年07月16日 星期三 11:05
 */
public class RepeatLineValidator<T> implements ImportValidator<T> {
    private String uniqueValidateIdKey;

    public RepeatLineValidator(String uniqueValidateIdKey) {
        this.uniqueValidateIdKey = uniqueValidateIdKey;
    }


    @Override
    public String validate(ImportDataWarp<T> cuxImportDataWarp, ImportValidatorContext<T> cuxImportValidatorContext) {
        T currData = cuxImportDataWarp.getData();
        try {
            Object o = FieldUtils.readField(currData, uniqueValidateIdKey, true);
            if (Objects.isNull(o)) {
                return "唯一性字段值为空";
            }
            String s = o.toString();
            List<ImportDataWarp<T>> alreadyValidatedImportDataWarpList = cuxImportValidatorContext.getAlreadyValidatedImportDataWarpList();
            for (ImportDataWarp<T> item : alreadyValidatedImportDataWarpList) {
                T data = item.getData();
                Object temp = FieldUtils.readField(data, uniqueValidateIdKey, true);
                // 已有数据中，该字段为空时，跳过判断
                if (Objects.isNull(temp)) {
                    continue;
                }
                String tempStr = temp.toString();
                if (Objects.equals(tempStr, s)) {
                    return "存在重复" + s + "行";
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return "未找到属性" + uniqueValidateIdKey;
        }
        return Strings.EMPTY;
    }
}